﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using dotNetDR_OAuth2.Sample.MVC.Controllers;

namespace dotNetDR_OAuth2.Sample.MVC
{
    public class DebugToolFormModelBinder : IModelBinder
    {

        #region IModelBinder 成员

        object IModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var form = controllerContext.HttpContext.Request.Form;

            if (HasNull(form["accessToken"],
                form["wbType"],
                form["httpMethod"],
                form["apiUrl"]))
            {
                return null;
            }

            DebugToolFormModel result = new DebugToolFormModel();

            result.accessToken = form["accessToken"];
            result.wbType = form["wbType"];
            result.httpMethod = form["httpMethod"];
            result.apiUrl = form["apiUrl"];
            result.kv = new Dictionary<string, string>();

            if (!string.IsNullOrEmpty(form["k"]))
            {
                var k2 = form.GetValues("k");
                var v2 = form.GetValues("v");

                for (int i = 0; i < k2.Length; i++)
                {
                    if (!string.IsNullOrEmpty(k2[i]))
                    {
                        result.kv.Add(k2[i], v2[i]);
                    }
                } 
            }

            return result;
        }

        #endregion

        private bool HasNull(params string[] param)
        {
            foreach (var item in param)
            {
                if (string.IsNullOrEmpty(item))
                {
                    return true;
                }
            }

            return false;
        }
    }
}